/**
 * 网络请求封装
 * 基于uni.request的二次封装，统一处理请求和响应
 */

// 基础配置
const BASE_URL = 'http://localhost:8080/api' // 根据实际后端地址调整
const TIMEOUT = 10000

// 请求拦截器
const requestInterceptor = (options) => {
  // 添加token
  const token = uni.getStorageSync('token')
  if (token) {
    options.header = options.header || {}
    options.header.Authorization = `Bearer ${token}`
  }
  
  // 添加基础URL
  if (!options.url.startsWith('http')) {
    options.url = BASE_URL + options.url
  }
  
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  if (statusCode === 200) {
    // 业务逻辑成功
    if (data.code === 200) {
      return data.data
    } else {
      // 业务逻辑错误
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
      })
      throw new Error(data.message)
    }
  } else if (statusCode === 401) {
    // 未授权，清除token并跳转登录
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.navigateTo({
      url: '/pages/auth/login'
    })
    throw new Error('未授权')
  } else {
    // 网络错误
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
    throw new Error('网络错误')
  }
}

/**
 * 统一请求方法
 * @param {Object} options - 请求配置
 * @returns {Promise} - 返回Promise对象
 */
export const request = (options) => {
  return new Promise((resolve, reject) => {
    // 处理请求配置
    options = requestInterceptor(options)
    
    uni.request({
      ...options,
      timeout: TIMEOUT,
      success: (response) => {
        try {
          const result = responseInterceptor(response)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 快捷方法
export const get = (url, params = {}) => {
  return request({
    url,
    method: 'GET',
    data: params
  })
}

export const post = (url, data = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

export const put = (url, data = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

export const del = (url, data = {}) => {
  return request({
    url,
    method: 'DELETE',
    data
  })
}

export default {
  request,
  get,
  post,
  put,
  del
}